package com.itheima.servlet;

import com.itheima.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

@WebServlet("/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取添加的学生属性
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        //封装成学生对象
        Student stu = new Student(name,Integer.parseInt(age));

        //将数据写入到文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IdeaProjects\\JavaWeb\\day07_sms\\src\\stu.txt",true));
        bw.write(name + "," + age);
        bw.newLine();
        bw.close();

        //给出提示并重定向到index.jsp页面
       response.getWriter().write("添加成功");
        response.setHeader("Refresh","1;URL="+request.getContextPath()+"/index.jsp");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
